//
//  MeViewController.m
//  MRBang
//
//  Created by 铅笔 on 15/12/14.
//  Copyright © 2015年 杭州易网新科技. All rights reserved.
//

#import "MeViewController.h"
#import "SetPersonMessageVC.h"//设置个人信息
#import "LoginViewController.h"//登录
#import "RewaradTskVC.h"//奖励任务
#import "PasswordSetVC.h"//密码管理
#import "CardRecordViewController.h"//信用卡办卡记录
#import "MyTradingRecordVC.h"//我的交易记录
#import "OneKeyRepaymentVC.h"//一键还款
#import "MyAccountVC.h"//我的账户
#import "MoreMessageVC.h"//更多 个人信息

#import "DrawGesturePasswordVC.h"//绘制手势密码锁

@interface MeViewController ()<UITableViewDataSource,UITableViewDelegate>

{
    UIView *view_topSubviewBG;//头部视图界面 背景
    UIButton *buttom_avater;
    UILabel *label_leftTitleBalance;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *mutableArray_data;//存放六个数据
@property (nonatomic,strong) NSDictionary *dictionary_info;//用户信息

@end

@implementation MeViewController

- (NSMutableArray *)mutableArray_data
{
    if (!_mutableArray_data) {
        _mutableArray_data = [[NSMutableArray alloc] init];
    }
    return _mutableArray_data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_EVERYVIEWBG;
    
    //    手势问题
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipe)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipe];
    
    UISwipeGestureRecognizer *toleftswipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipe)];
    toleftswipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:toleftswipe];
}

- (void) viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden  = NO;
    
    self.dictionary_info = nil;
    
//    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"memberid"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //清除缓存
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDisk];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"head"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //创建子视图
    [self initWithAllSubviews];

    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"]) {
        LoginViewController *loginView = [[LoginViewController alloc] init];
        loginView.fromeWhere = @"meCenter";
        [self.navigationController pushViewController:loginView animated:YES];
    }
    else
    {
        //网络数据请求
        [self DataRequestUserInfo];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"indexTabbar"] isEqualToString:@"3"]) {
        
        DrawGesturePasswordVC *drawGestureView = [[DrawGesturePasswordVC alloc] init];
        
        drawGestureView.str_fromWhere = @"meCenterGesture";
        [self.navigationController pushViewController:drawGestureView animated:YES];
    }
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden  = NO;
}

#pragma mark ---- 创建子视图
- (void) initWithAllSubviews
{
    //头部 视图
    [self initWithTopSubviews];
    
    //tableView 视图
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,view_topSubviewBG.bottom, kScreenWidth, kScreenHeight-view_topSubviewBG.height-39)];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = [BaseViewController colorWithHexString:@"#eeeff1"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark --- 创建头部视图界面
- (void) initWithTopSubviews
{
    view_topSubviewBG = [[UIView alloc] initWithFrame:CGRectMake(0, -10, kScreenWidth, kScreenWidth*0.6)];
    [self.view addSubview:view_topSubviewBG];
    
    UIImageView *bg=[[UIImageView alloc] initWithFrame:CGRectMake(0,0, view_topSubviewBG.width, view_topSubviewBG.height )];
    bg.image=[UIImage imageNamed:@"metopback"];
    [view_topSubviewBG addSubview:bg];
    
    //头像
    buttom_avater = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-40, kScreenWidth/4-40, 80, 80)];
    [view_topSubviewBG addSubview:buttom_avater];
    
    buttom_avater.layer.cornerRadius = buttom_avater.frame.size.width/2;
    buttom_avater.clipsToBounds = YES;
    [buttom_avater addTarget:self action:@selector(editPersonMessage) forControlEvents:UIControlEventTouchUpInside];
    
    //更多
    UIButton *buttom_more = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-126*PROPORTION_WIDTH,76*PROPORTION_WIDTH, 100*PROPORTION_WIDTH, 42*PROPORTION_WIDTH)];
    [view_topSubviewBG addSubview:buttom_more];
    
    buttom_more.backgroundColor = [BaseViewController colorWithHexString:@"#121a1e"];
    buttom_more.layer.cornerRadius = 10.0;
    buttom_more.clipsToBounds = YES;
    [buttom_more.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_22]];
    [buttom_more setTitle:@"更多" forState:UIControlStateNormal];
    [buttom_more setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [buttom_more addTarget:self action:@selector(morePersonMessageAction) forControlEvents:UIControlEventTouchUpInside];
    
    //设置
    UIButton *buttom_set = [[UIButton alloc] initWithFrame:CGRectMake(315*PROPORTION_WIDTH,10*PROPORTION_WIDTH+buttom_avater.bottom, 100*PROPORTION_WIDTH, 41*PROPORTION_WIDTH)];
    [view_topSubviewBG addSubview:buttom_set];
    buttom_set.backgroundColor = [BaseViewController colorWithHexString:@"#121a1e"];
    buttom_set.layer.cornerRadius = 10.0;
    buttom_set.clipsToBounds = YES;
    [buttom_set.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_22]];
    [buttom_set setTitle:@"设置" forState:UIControlStateNormal];
    [buttom_set setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"head"]) {
       [buttom_avater sd_setBackgroundImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"head"]] forState:UIControlStateNormal placeholderImage:nil];
    }
    else
    {
     [buttom_avater setBackgroundImage:[UIImage imageNamed:@"ic_mrbang"] forState:UIControlStateNormal];
    }
    
}

#pragma mark --- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   
    //label
    UILabel *label_leftTitle = [[UILabel alloc] init];
    [cell.contentView addSubview:label_leftTitle];
    label_leftTitle.font = [UIFont systemFontOfSize:30*PROPORTION_WIDTH];
    
    if (indexPath.row==0) {
      
        label_leftTitleBalance = [[UILabel alloc] init];
        [cell.contentView addSubview:label_leftTitleBalance];
        label_leftTitleBalance.font = [UIFont systemFontOfSize:30*PROPORTION_WIDTH];
        label_leftTitleBalance.text = [NSString stringWithFormat:@"0 元"];
        
        if (!self.dictionary_info) {
            label_leftTitleBalance.text = [NSString stringWithFormat:@"%@元", @"0"];
        }
        else
        {
            label_leftTitleBalance.text = [NSString stringWithFormat:@"%@元", self.dictionary_info[@"balance"]];
        }
        
        label_leftTitleBalance.textColor = [BaseViewController colorWithHexString:@"#E8482E"];
        label_leftTitleBalance.frame = CGRectMake(0,30*PROPORTION_WIDTH,kScreenWidth/2, 40*PROPORTION_WIDTH);
        label_leftTitleBalance.textAlignment = NSTextAlignmentCenter;
        
        //button
        UIButton *button_getMoney = [[UIButton alloc] initWithFrame:CGRectMake(label_leftTitleBalance.right, label_leftTitleBalance.y, label_leftTitleBalance.width, label_leftTitleBalance.height)];
        [cell.contentView addSubview:button_getMoney];
        [button_getMoney setTitle:@"昨日收益" forState:UIControlStateNormal];
        [button_getMoney setTitleColor:[BaseViewController colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        [button_getMoney.titleLabel setFont:[UIFont systemFontOfSize:30*PROPORTION_WIDTH]];
        
        //ver line
        UIView *view_verline  = [[UIView alloc] initWithFrame:CGRectMake(label_leftTitleBalance.right, 5, 1.0, 100*PROPORTION_WIDTH-10)];
        [cell.contentView addSubview:view_verline];
        view_verline.backgroundColor = [BaseViewController colorWithHexString:@"#EEEFF1"];
    }
    
    if (indexPath.row==1) {
        label_leftTitle.text = @"我的奖励任务";
        label_leftTitle.textColor = [BaseViewController colorWithHexString:@"#000000"];
        label_leftTitle.frame = CGRectMake(264*PROPORTION_WIDTH,30*PROPORTION_WIDTH+10,193*PROPORTION_WIDTH, 31*PROPORTION_WIDTH);
        label_leftTitle.textAlignment = NSTextAlignmentCenter;
        label_leftTitle.font = [UIFont systemFontOfSize:30*PROPORTION_WIDTH];
        
        UIView *view_line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
        [cell.contentView addSubview:view_line];
        view_line.backgroundColor = [BaseViewController colorWithHexString:@"#eeeff1"];
        
        //button
        UIButton *button_rightArrow = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-30,view_line.bottom+27*PROPORTION_WIDTH, 20, 20)];
        [cell.contentView addSubview:button_rightArrow];
        [button_rightArrow setImage:[UIImage imageNamed:@"return_right"] forState:UIControlStateNormal];
        
        //label
        UILabel *label_progress = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth-30-30,view_line.bottom+27*PROPORTION_WIDTH, 50, 20)];
        [cell.contentView addSubview:label_progress];
        label_progress.text = @"进度";
        label_progress.font = [UIFont systemFontOfSize:28*PROPORTION_WIDTH];
        label_progress.textColor = [BaseViewController colorWithHexString:@"#666666"];
    }
    if (indexPath.row==3||indexPath.row==2)
    {
        
      cell.backgroundColor = [BaseViewController colorWithHexString:@"#eeeff1"];
       NSArray *array_name = @[@[@"信用卡办卡记录",@"我的交易记录"],@[@"还款申请记录",@"我的账户"]];
       NSArray *array_img = @[@[@"Notepad",@"myChangeRecord"],@[@"payMoney",@"Profile"]];
       
       NSArray *array_nametemp,*array_imgtemp;
       
       array_nametemp = array_name[indexPath.row-2];
       array_imgtemp = array_img[indexPath.row-2];
       
       CGFloat buttonW = (kScreenWidth-3)/2;
       UILabel *label_text;
        label_text.backgroundColor = [UIColor greenColor];
       
       int count = 0;
       
       count = 2;
       
       CGFloat buttonY ;
        
        if (indexPath.row==2) {
            buttonY=3;
        }
        else
        {
            buttonY = 2;
        }
      
       for (int i=0; i<count; i++) {
           UIButton *button_temp = [[UIButton alloc] initWithFrame:CGRectMake((buttonW+1)*i, buttonY, buttonW,236*PROPORTION_WIDTH)];
           [cell.contentView addSubview:button_temp];
           button_temp.backgroundColor = [UIColor whiteColor];
           
           [button_temp setImageEdgeInsets:UIEdgeInsetsMake(-13, 0, 15, 0)];
           [button_temp setImage:[UIImage imageNamed:array_imgtemp[i]] forState:UIControlStateNormal];
           
           //文字
           label_text = [[UILabel alloc] initWithFrame:CGRectMake(0, button_temp.frame.size.height-50, buttonW, 20)];
           [button_temp addSubview:label_text];
           label_text.text = array_nametemp[i];
           label_text.textAlignment = NSTextAlignmentCenter;
           label_text.textColor = [BaseViewController colorWithHexString:@"#384056"];
           label_text.font = [UIFont systemFontOfSize:24*PROPORTION_WIDTH];
           
           //此处优待优化
          if (indexPath.row==2) {
               button_temp.tag = 50+i;
           }
           if (indexPath.row==3) {
               button_temp.tag = 60+i;
           }
          
           
           [button_temp addTarget:self action:@selector(clickDifferentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
       }
   }
    
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==1) {
        RewaradTskVC *rewardView = [[RewaradTskVC alloc] init];
        rewardView.str_ycaptcha = self.dictionary_info[@"ycaptcha"];
        rewardView.str_ycaptchanum = self.dictionary_info[@"ycaptchanum"];
        
        rewardView.str_rewuFirst = self.dictionary_info[@"renwu1"];
        rewardView.str_rewuSecond = self.dictionary_info[@"renwu2"];
        
        [self.navigationController pushViewController:rewardView animated:YES];
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 100*PROPORTION_WIDTH;
    }
    if (indexPath.row == 1)
    {
        return  60;
    }
   
    else
    {
        return 240*PROPORTION_WIDTH;
    }
}

#pragma mark ---- 点击不同的按钮进入不同的界面
- (void) clickDifferentButtonAction:(UIButton *)sender
{
    if (sender.tag==10) {
        
    }
    if (sender.tag==11) {
        
    }

    if (sender.tag==12) {
        //密码管理
        PasswordSetVC *passwdView = [[PasswordSetVC alloc] init];
        [self.navigationController pushViewController:passwdView animated:NO];
        
    }
    if (sender.tag==50) {
        //办卡记录
        CardRecordViewController *cardRecordView = [[CardRecordViewController alloc] init];
        [self.navigationController pushViewController:cardRecordView animated:YES];
    }

    if (sender.tag==51) {
        //我的交易记录
        MyTradingRecordVC *myTradingView = [[MyTradingRecordVC alloc] init];
        [self.navigationController pushViewController:myTradingView animated:YES];
        
    }

    if (sender.tag==60) {
        //一键还款
        OneKeyRepaymentVC *oneKeyView = [[OneKeyRepaymentVC alloc] init];
        [self.navigationController pushViewController:oneKeyView animated:NO];
        
    }
    if (sender.tag==61) {
        
        //我的账户
        MyAccountVC *myAccountView = [[MyAccountVC alloc] init];
        
        if (![self.dictionary_info[@"balance"] isEqual:[NSNull null]]) {
            if (self.dictionary_info[@"balance"]==nil) {
                myAccountView.str_balance = @"0.00元";
            }
            else
            {
               myAccountView.str_balance = [NSString stringWithFormat:@"%@元",self.dictionary_info[@"balance"]];
            }
        }
        else
        {
            myAccountView.str_balance = @"0.00元";
        }
        [self.navigationController pushViewController:myAccountView animated:YES];
    }
}

#pragma mark --- 进入个人信息设置
- (void) editPersonMessage
{
    SetPersonMessageVC *personMess = [[SetPersonMessageVC alloc] init];
    if (![self.dictionary_info[@"nickname"] isEqual:[NSNull null]]) {
        personMess.str_name = self.dictionary_info[@"nickname"];
    }
    
    if (![self.dictionary_info[@"name"] isEqual:[NSNull null]]) {
        personMess.str_realName = self.dictionary_info[@"name"];
    }
    else
    {
        personMess.str_realName = @"no";
    
    }
    personMess.str_avatarUrl = self.dictionary_info[@"head"];
    personMess.str_telPhone = self.dictionary_info[@"mobile"];
    [self.navigationController pushViewController:personMess animated:NO];
}

- (void) morePersonMessageAction
{
    MoreMessageVC *moreView = [[MoreMessageVC alloc] init];
    [self.navigationController pushViewController:moreView animated:YES];
}

- (void)leftSwipe {
    if (self.tabBarController.selectedIndex == 0) {
        //这边根据需求写
        return;
    }
    self.tabBarController.selectedIndex--;
}

- (void)rightSwipe {
    if (self.tabBarController.selectedIndex == self.tabBarController.childViewControllers.count-1) {
        //这边根据需求写
        return;
    }
    self.tabBarController.selectedIndex++;
}

#pragma mark --- 用户信息查询
- (void) DataRequestUserInfo
{
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
        NSLog(@"没有网络");
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@member/info",MRAPI];
        NSDictionary *paras_info = @{@"memberid":[[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"]};

        [[HttpRequest shardWebUtil] getNetworkRequestURLString:strUrl parameters:paras_info success:^(id obj) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
                
                self.dictionary_info = obj;
                
                [buttom_avater sd_setBackgroundImageWithURL:[NSURL URLWithString:self.dictionary_info[@"head"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"ic_mrbang"]];
                
                [[NSUserDefaults standardUserDefaults] setObject:self.dictionary_info[@"head"] forKey:@"head"];
                [[NSUserDefaults standardUserDefaults]  synchronize];
                
                if (![self.dictionary_info[@"idcard"] isEqual:[NSNull null]]) {
                    [[NSUserDefaults standardUserDefaults] setObject:self.dictionary_info[@"idcard"] forKey:@"idcard"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                   }
                
                //3个 button
                NSArray *array_title = @[@"手机",@"身份证",@"密码管理"];
                NSMutableArray *array_images = [[NSMutableArray alloc] init];
                
                if (self.dictionary_info[@"mobile"]) {
                    [array_images addObject:@"telphoneSelected"];
                }
                else
                {
                    [array_images addObject:@"phone"];
                }
                
                if (self.dictionary_info[@"idcard"]) {
                    [array_images addObject:@"v-card_ed"];
                }
                else
                {
                    [array_images addObject:@"v-card"];
                }
                
                //密码管理
                int  ispasspwd=[[[NSUserDefaults standardUserDefaults]objectForKey:@"issetpaypassword"] intValue];
                
                if (ispasspwd == 1) {
                    [array_images addObject:@"locked_ed"];
                }
                else
                {
                    [array_images addObject:@"locked"];
                }
                
                CGFloat buttonW = (kScreenWidth-155*PROPORTION_WIDTH*2)/3;
                CGFloat buttonH = 60*PROPORTION_WIDTH;
                
                for (int i=0; i<3; i++) {
                    UIButton *button_temp = [[UIButton alloc] initWithFrame:CGRectMake(155*PROPORTION_WIDTH+(buttonW+2)*i,view_topSubviewBG.bottom-buttonH-10, buttonW, buttonH)];
                    [view_topSubviewBG addSubview:button_temp];
                    [button_temp setTitle:array_title[i] forState:UIControlStateNormal];
                    [button_temp setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [button_temp.titleLabel setFont:[UIFont systemFontOfSize:Font_SIZE_22]];
                    [button_temp setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
                    [button_temp setImage:[UIImage imageNamed:array_images[i]] forState:UIControlStateNormal];
                    button_temp.tag = 10+i;
                    [button_temp addTarget:self action:@selector(clickDifferentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                }

                
                [self.tableView reloadData];
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            [BaseViewController showMessage:@"请求超时"];
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        }];
    }
}

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.tableView removeFromSuperview];
    [view_topSubviewBG removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

@end
